// 扩展 String 对象，提供格式化方法
String.prototype.format = function () {
    var args = arguments;
    return this.replace(/\{(\d+)\}/g,
        function (m, i) {
            return args[i];
        });
};


// 超时提示器。在超时后进行等待提示
var outer = {
    alerter: null,
    showTimer: null,
    closeTimer: null,
    show: function () {
        if (this.alerter == null) {
            var left = ($(window).width() - 300) / 2;
            var top = ($(window).height() - 300) / 2;
            this.alerter = $("div.divTimeoutAlert").css("top", top).css("left", left);
        }
        // 同时多次调用时，重置Timer，保证以最后一次为准
        if (this.showTimer != null) {
            clearTimeout(this.showTimer);
        }
        this.showTimer = setTimeout("outer.alerter.show('normal')", 1000);
    },
    close: function () {
        clearTimeout(this.showTimer);
        this.clearCloseTimer();
        //this.closeTimer = setTimeout("outer.clearCloseTimer()", 700);
    },
    clearCloseTimer: function () {
        this.alerter.hide("normal");
        //clearTimeout(this.closeTimer);
    }
};
function ajaxMethod(method, eventHandler, context) {
    outer.show();
    // 设定超时提示
    $.post(location.href, { Action: method },
        function (data) {
            // 结束超时提示
            outer.close();
            // 处理数据
            if (!checkError(data)) { eventHandler(data, context); }
        });
}

// 检查Ajax结果是否包含错误提示
function checkError(data) {
    if (data.indexOf("对不起") > -1) {
        alert(data);
        return true;
    }
    return false;
}

// 为jQuery扩展自定义的绑定方法
$.fn.extend({
    bindInfo: { member: "dataMember" },
    bindData: function (tag, data, valueName, textName, defaultNull, events) {
        this.empty();
        if (!data instanceof Array) {
            throw alert("这真不是数组");
        }
        var op;
        if (defaultNull) {
            this.append($(tag));
        }
        for (var i = 0; i < data.length; i++) {
            op = data[i];
            op = $(tag)
                .data(this.bindInfo.member, op)
                .val(op[valueName])
                .html((textName instanceof Function) ? textName(op) : op[textName]);
            this.append(op);
            if (events instanceof Function) { events(op); }
        }
        this.temptest = "test";
        return this;
    },
    dataMember: function () {
        return this.data(this.bindInfo.member);
    },
    dataMembers: function () {
        var children = this.children(),
            dataSource = [];
        for (var i = 0; i < children.length; i++) {
            var t = $(children[i]).dataMember();
            dataSource.push(t);
        }
        return dataSource;
    },
    valTrim: function () {
        if (this instanceof jQuery) {
            return $.trim(this.val());
        } else {
            return this;
        }
    },
    // for selector
    selected: function () {
        if (arguments.length == 1) {
            // 记录修改前状态
            var state = this.hasClass('selected');
            arguments[0] ? this.addClass('selected') : this.removeClass('selected');
            if (state != arguments[0]) {
                // 状态被修改，则触发事件
                this.trigger('selectionChanged');
            }
        }
        return this.hasClass('selected');
    }
});

// 为行提供选中外观
var selector = {
    $lastTarget: null,
    select: function ($target) {
        if (!($target instanceof jQuery) && $target.tagName == null) {
            $target = $(this);
        }
        var parent = $target.parent();
        if (!parent.hasClass('multiple')) {
            var lastTarget = parent.data('lastSelected');
            if (lastTarget != null) {
                lastTarget.selected(false);
            }
            $target.selected(true);
        } else {
            if (event.shiftKey) {
                var lastTarget = parent.data('lastSelected');
                var state = -1; // -1 为未启动，0 为由当前项启动，1 为由上一项启动, 2 为已结束
                parent.children().each(function (i, o) {
                    var $o = $(o);
                    if (state < 0) {
                        // 如果还未启动
                        if ($o.val() == lastTarget.val()) {
                            state = 1;
                        } else if ($o.val() == $target.val()) {
                            state = 0;
                        }
                    }
                    if (state > -1 && state < 2) {
                        $o.selected(true);

                        // 判断是否结束选中
                        if (state == 0 && $o.val() == lastTarget.val()) {
                            state = 2;
                        } else if (state == 1 && $o.val() == $target.val()) {
                            state = 2;
                        }
                    }
                });
                return;
            } else {
                $target.selected(!$target.selected());
            }
        }
        parent.data('lastSelected', $target);
    }
};

/**
 * context 上下文对象
 * 用于记录当前的审批组和当前节点
 */
var context = {
    _data: function () {
        if (arguments.length == 1) {
            return context[arguments[0]];
        } else {
            context[arguments[0]] = arguments[1];
        }
    },
    approvers: function () {
        var approvers_a = $(arguments[0]);
        // 如果有参数，并且参数为一个a标签
        if (approvers_a.length > 0 && approvers_a.is("a")) {
            // 试图从a标签上获取Approvers相关参数
            // 参数名在onClick_ulNodes_a方法中
            var approversID = approvers_a.attr("ApproversID");
            var approversTypeID = approvers_a.attr("ApproversTypeID");
            if (approversID != null && approversTypeID != null) {
                context._data("_approvers", [approversID, approversTypeID]);
            }
        }
        return context._data("_approvers");
    },
    nodeID: function () {
        var node_a = $(arguments[0]);
        // 如果有参数，并且参数为一个a标签
        if (node_a.length > 0 && node_a.is("a")) {
            // 试图从a标签上获取NodeID参数
            context.node(node_a);
            var nodeid = node_a.attr("NodeID");
            if (nodeid != null) {
                context._data("_nodeID", nodeid);
            }
        }
        return context._data("_nodeID");
    },
    node: function () {
        var node_a = arguments[0];
        // 如果有参数，并且参数为一个a标签
        if (node_a.length > 0) {
            context._data("_node", node_a);
        }
        return context._data("_node");
    },
    deptSource: function () {
        var source = context._data("_deptSource");
        if (source == null) {
            ajaxMethod("GetDeptSource()", function (data) {
                context._data("_deptSource", $.evalJSON(data));
                var usercallback = arguments[0];
                if (usercallback != null && usercallback instanceof Function) {
                    usercallback();
                }
            });
        }
        return source;
    },
    sltedDepts: function () {
        var source = arguments[0]
        if (source instanceof Array) {
            context._data('_sltedDepts', source);
        }
        return context._data('_sltedDepts');;
    }
};

/**
 * Node
 * Approvers
 * Group
 */
function onClick_ulNodes_a() {
    if (arguments.length != 2) {
        ajaxMethod("GetHighers(" + context.nodeID(this) + ")", onClick_ulNodes_a);
    } else {
        // 回调返回
        var higherList = $.evalJSON(arguments[0]);
        if (higherList.length > 0) {
            $("#ulHighers").bindData("<li></li>", higherList, "HigherID",
                function (higher) {
                    return $("<a href='javascript:void();' ApproversID='{0}' ApproversTypeID='{1}' >{2}</a>".format(higher.ID, higher.HigherType, higher.HigherName))
                        .click(onclick_higher)
                });
            $("#ulHighers a:eq(0)").click();
        } else {
            $("#ulHighers").empty().append($("<li>没有找到操作组</li>"));

            $("#divUsers, #divBtns, #divSelects, #divGroups")
                .hide("normal");
        }
    }
}
function onclick_higher() {
    context.approvers(this);
    approvers.refresh(true);
}
function onChange_groupFilter() {
    ajaxMethod("GetCheckGroups(" + context.approvers()[0] + "," + $("#groupFilter").val() + ")", function (data) {
        $("#dplGroups").bindData("<option></option>", $.evalJSON(data), "GroupID", "GroupName");
        // 绑定完成后，默认选择第一项，并绑定内容
        $("#dplGroups option:eq(0)").attr('selected', 'selected');
        $("#dplGroups").change();
    });
}
function bindCheckedUsers(data) {
    if (data == null) {
        return;
    }
    $("#selectCheckedUsers").bindData(
        "<option></option>", data, "UserID", "ChineseName");

    changeSaveState();
}
function bindGroup(g) {
    $("#dplGroups").val(g.GroupID);
}
/**
 * Group
 * Company
 * Deptment
 * Users
 */
function onChange_dplGroups() {
    approvers.refresh();
}
function onChange_dplCom() {
    var $dplCom = $(this),
        comId = $dplCom.valTrim()
    if (comId == "") { $("#dplDepts").empty(); $("#selectUsers").empty(); return; } // 第一个空
    ajaxMethod("GetDepts(" + comId + ")", bindDept);
}
function bindDept(data) {
    $("#dplDepts").bindData("<option></option>", $.evalJSON(data), "DeptID", "DeptName", true);
    refreshUsers();
}
function onChange_dplDepts() {
    refreshUsers();
}
function refreshUsers() {
    if (arguments.length == 0) {
        var comId = $("#dplCom").valTrim();
        if (comId == null || comId == "") {
            return;
        }
        var deptId = $("#dplDepts").val();
        deptId = deptId == null ? "" : $.trim(deptId);

        ajaxMethod("GetUsers(" + deptId + "," + comId + ")", refreshUsers);
    } else {
        var data = arguments[0], // return type Users Array
            checkedData = $("#selectCheckedUsers").dataMembers(), // return type Users Array
            item;
        if (data != null) {
            data = $.evalJSON(data);
        }
        for (var x in checkedData) {
            item = checkedData[x];
            for (var y in data) {
                if (item.UserID == data[y].UserID) {
                    data.splice(y, 1);
                    break;
                }
            }
        }
        $("#selectUsers").bindData("<option></option>", data, "UserID", "ChineseName");
    }
}
/**
 * Save / input
 */
function changeSaveState() {
    return; // 暂时禁用
    if ($("#selectCheckedUsers").children().length < 1) {
        $("#btnSave").attr("Disabled", "Disabled");
    } else {
        $("#btnSave").removeAttr("Disabled");
    }
}
function onClick_btnSave() {
    var approvers = context.approvers();
    if (approvers == null) { return; }
    var arg = {
        ApproversID: approvers[0],
        ApproversTypeID: approvers[1],
        Members: [],
        GroupID: -1
    };
    var methodName;
    switch (arg.ApproversTypeID) {
        case "1":
        case "5":
            $('#selectCheckedUsers').children().each(function (i, t) {
                arg.Members.push(t.value)
            });
            break;
        case "6":
            deptGroup.pushSelectedDepts(arg.Members);
            break;
    }
    switch (arg.ApproversTypeID) {
        case "5": // Group
            arg.GroupID = $("#dplGroups").val()[0];
            methodName = "SaveGroup";
            break;
        case "1": // Value
            methodName = "SaveValue";
            break;
        case "6": // DeptGroup
            var values = deptGroup.sltDeptGroups().val();
            if (values == null) {
                values = $("#sltDeptGroups option:eq(0)").val();
            }
            if (values == null) {
                alert('请在左侧组选择框中选择任意一组');
                return;
            }
            arg.GroupID = values instanceof Array ? values[0] : values;
            methodName = "SaveDeptGroup";
            break;
    }

    ajaxMethod(methodName + "(" + $.toJSON(arg) + ")", function (data) {
        $(".divAlertResult").show("normal");
        setTimeout("$('.divAlertResult').hide('normal')", 2000);
    });
}
/**
 * User Select
 * Input Button
 */
function moveOptions(go, to) {
    var checkedSource = $(to).dataMembers();
    var userSource = $(go).dataMembers();

    $(go + " option:selected").each(function (i, t) {
        var $t = $(t),
            rept = false;
        for (var i in checkedSource) {
            if (checkedSource[i].UserID == $t.dataMember().UserID) {
                // 如果发现重复对象，则删除待选对象
                $t.remove();
                rept = true;
                break;
            }
        }
        if (!rept) {
            $t.appendTo(to);
        }
    });

    changeSaveState();
}
function onClick_btnCheck() {
    switch (context.approvers()[1]) {
        case '6':
            deptGroup.moveDepts(true);
            break;
        case '1':
        case '5':
            moveOptions("#selectUsers", "#selectCheckedUsers");
            break;
    }
}
function onClick_btnUncheck() {
    switch (context.approvers()[1]) {
        case '6':
            deptGroup.moveDepts(false);
            break;
        case '1':
        case '5':
            moveOptions("#selectCheckedUsers", "#selectUsers");
            break;
    }
}

var deptGroup = {
    // Dom Properties
    _getProperty: function(name){
        if (!deptGroup.hasOwnProperty(name)){
            deptGroup[name] = $('#' + name);
        }
        return deptGroup[name];
    }
    sltComps: function () { return deptGroup._getProperty('dg_sltComps'); },
    sltDepts: function () { return deptGroup._getProperty('dg_sltDepts'); },
    sltParentDepts: function () { return deptGroup._getProperty('sltParentDepts'); },
    ckbsDepts: function () { return deptGroup._getProperty('ckbsDepts'); },

    //sltDeptGroups: function () { return deptGroup._getProperty('sltDeptGroups'); },
    
    // Properties
    getSltedCompID: function() { return deptGroup.sltComps().val(); },
    getSltedDeptID: function() { return deptGroup.sltDepts().val(); },
    // Event Handlers
    onChange_sltComps : function() {
        // 选择公司时刷新部门内容
        // 同时默认选中第一部门
        with(deptGroup){
            ajaxMethod('GetDepts(' + getSltedCompID() + ')', function(data) {
                sltDepts().bindData("<option></option>", $.evalJSON(data), "DeptID", "DeptName", true);
                sltDepts().find('option:eq(0)').attr('selected', 'selected');
                sltDepts().change();
            });
        }
    },
    onChange_sltDepts: function() {
        // 选择部门时刷新人员
        // 同时默认选中第一人员
        with(deptGroup) {
            ajaxMethod("GetUsers(" + getSltedDeptID() + "," + getSltedDeptID() + ")", function(data) {
                data = $.evalJSON(data);



                var data = arguments[0], // return type Users Array
                    checkedData = $("#selectCheckedUsers").dataMembers(), // return type Users Array
                    item;


                if (data != null) {
                    data = $.evalJSON(data);
                }
                for (var x in checkedData) {
                    item = checkedData[x];
                    for (var y in data) {
                        if (item.UserID == data[y].UserID) {
                            data.splice(y, 1);
                            break;
                        }
                    }
                }
                $("#selectUsers").bindData("<option></option>", data, "UserID", "ChineseName");
            });
        }
    },
    // Methods 2
    


    // Methods
    getFindDeptsFilter: function (parentDeptID) {
        if (parentDeptID >= 0) {
            // 按部门搜索
            return function (o, i) {
                return o.ParentDeptID == parentDeptID;
            };
        } else {
            // 使用公司搜索
            return function (o, i) {
                return o.CompanyID == -parentDeptID;
            }
        }
    },
    findDepts: function (parentDeptID) {
        // 查找所有该部门的子部门
        var source = context.deptSource();
        var newsource = $.grep(source, deptGroup.getFindDeptsFilter(parentDeptID));
        for (var i = 0; i < newsource.length; i++) {
            newsource.concat(deptGroup.findDepts(newsource[i].DeptID));
        }
        return newsource;
    },
    findDept: function (deptID) {
        // 查找指定的部门
        return $.grep(context.deptSource(), function (o, i) {
            return o.DeptID == deptID;
        });
    },
    findParents: function (parentDeptID) {
        // 级联查找所有上级部门
        var depts = $.grep(context.deptSource(), function (o, i) {
            return o.DeptID == parentDeptID;
        });
        if (depts.length > 0) {
            depts.concat(deptGroup.findParents(depts[0].ParentDeptID));
        }
        return depts;
    },
    getGroups: function () {
        ajaxMethod("GetDeptGroups(" + context.approvers()[0] + "," + $("#sltGroupFilter").val() + ")", function (data) {
            with (deptGroup) {
                sltDeptGroups().bindData("<option></option>", $.evalJSON(data), "ID", "Name");
                sltDeptGroups().find('option:eq(0)').attr('selected', 'selected');
                sltDeptGroups().change();
            }
        });
    },
    bindParentDepts: function () {
        // 如果为空则表示为第一次获取
        // 则需要通过回调处理
        var source = context.deptSource(deptGroup.bindParentDepts);
        if (source == null) {
            return;
        }
        deptGroup.sltParentDepts().bindData("<option></option>", source, "DeptID", "DeptName", false);
        //
        deptGroup.sltParentDepts().change();
    },
    bindChildDepts: function () {
        with (deptGroup) {
            // 获取父部门ID
            var parentDeptID = sltParentDepts().val();
            if (parentDeptID == null || parentDeptID.length < 1) {
                return;
            }
            var depts = findDepts(parentDeptID);
            if (depts.length == 0) {
                // 如果没有找到子部门，则说明为最底层部门
                depts = findDept(parentDeptID);
            }
            ckbsDepts().bindData("<li></li>", depts, "DeptID", "DeptName", false,

            function (l) {
                l.bind('selectionChanged', function () {
                    var $this = $(this);
                    var childDepts = deptGroup.findDepts($this.dataMember().DeptID);
                    deptGroup.bindSelectedDept(childDepts, $this.selected());
                    if (!$this.selected()) {
                        // 如果状态为非选中状态，则同步去除所有上级部门的选中状态
                        var parents = deptGroup.findParents($this.dataMember().ParentDeptID);
                        for (var i = 0; i < parents.length; i++) {
                            $('li[value={0}]'.format(parents[i].DeptID)).selected(false);
                        };
                    }
                });
            });
        }
    },
    bindSelectedDept: function (members, selected) {
        if (members == null) {
            return;
        }
        var $li, childDepts;
        for (var i = 0; i < members.length; i++) {
            $li = $('li[value={0}]'.format(members[i].DeptID));
            if ($li.selected() != selected) {
                $li.click();
            }
        }
    },
    pushSelectedDepts: function (members) {
        deptGroup.ckbsDepts().find('li.selected').each(function (i, o) {
            members.push($(o).val());
        });
    },
    // EventHandlers
    onChange_ParentDepts: function () {
        deptGroup.bindChildDepts();
        deptGroup.bindSelectedDept(context.sltedDepts(), true);
    },

    onChange_sltGroupFilter: function () {
        deptGroup.getGroups();
    },
    onChange_sltDeptGroups: function () {
        approvers.refresh();
    }
};

// 操作组和审批信息主控制
var approvers = {
    refreshPanel: function (showSelecter, hideSelecter) {
        $(showSelecter).show('normal');
        $(hideSelecter).hide('normal');
    },
    refresh: function (refreshGroup) {
        // 刷新操作组
        // refreshGroup: 是否前置刷新人员组或部门组信息
        var idAndType = context.approvers();
        var method, arg = idAndType[0];

        switch (idAndType[1]) {
            case "5": // Group
                // 修改界面提示
                $("#divUsers h3").text("已选该组成员");
                approvers.refreshPanel(
                    '#divGroups, #divUsers, #divSelects, #divBtns, #btnCheck, #btnUncheck',
                    '#divDeptGroups, #divSelectedDepts, #type9');

                method = "GetGroup";
                if (refreshGroup) {
                    onChange_groupFilter();
                    return;
                }
                var values = $("#dplGroups").val();
                if (values == null) {
                    values = $("#dplGroups option:eq(0)").val();
                }
                if (values == null) {
                    // 没有组，则放弃刷新组信息
                    // 清空相关内容
                    $('#selectCheckedUsers').empty();
                    return;
                }
                arg += "," + (values instanceof Array ? values[0] : values);
                break;
            case "1": // Value
                // 调整界面
                $("#divUsers h3").text("已选人员");
                approvers.refreshPanel(
                    '#divUsers, #divSelects, #divBtns, #btnCheck, #btnUncheck',
                    '#divGroups, #divDeptGroups, #divSelectedDepts, #type9');

                method = "GetHigher";
                break;
            case "9":
                // 该类型不需要处理
                // 隐藏所有面板并阻断方法
                approvers.refreshPanel('#type9', '.divSetHigher');
                return;
            case "6":
                // 如果选择器没有初始化。则初始化部门选择器
                if ($("#sltParentDepts option").length < 1) {
                    deptGroup.bindParentDepts();
                }
                approvers.refreshPanel(
                    '#divDeptGroups, #divSelectedDepts, #divBtns',
                    '#divUsers, #divSelects, #divGroups, #divSelects, #type9, #btnCheck, #btnUncheck');

                method = "GetDeptGroup";
                if (refreshGroup) {
                    deptGroup.onChange_sltGroupFilter();
                    return;
                }
                var values = deptGroup.sltDeptGroups().val();
                if (values == null) {
                    values = $("#sltDeptGroups option:eq(0)").val();
                }
                if (values == null) {
                    // 没有组，则清空相关信息，放弃刷新
                    deptGroup.sltParentDepts().val();
                    return;
                }
                arg += "," + (values instanceof Array ? values[0] : values);
                break;
        }

        ajaxMethod(method + "(" + arg + ")", approvers.bind, idAndType[1]);
    },
    bind: function (data, type) {
        data = $.evalJSON(data);
        // 是有需要最后刷新用户
        var needRefresh = false;
        // 相关类型ID对应的审批组可参阅数据库中类型表
        switch (type) {
            case "1":
                // 绑定审批人到已选用户表
                // 并刷新待选用户
                bindCheckedUsers(data);
                needRefresh = true;
                break;
            case "5":
                // 绑定组
                var group = data;
                if (group != null) {
                    // 显示当前组的审批人
                    $("#currentGroup").text(group.GroupName);
                    $("#currentGrouper").text(group.Higher.ChineseName);
                    // 绑定成员
                    bindCheckedUsers(group.Members);
                } else {
                    // 如果没有配置成员，
                    $("#selectCheckedUsers").empty(); // 强制清空
                }
                needRefresh = true;
                break;
            case "6":
                var _deptGroup = data;
                // 显示当前组的审批人
                $("#divGroupInfo #Span1").text(_deptGroup.Name);
                $("#divGroupInfo #Span2").text(_deptGroup.User.ChineseName);
                // 绑定成员
                context.sltedDepts(_deptGroup.Members);
                deptGroup.onChange_ParentDepts();
                break;
            default:
                // 暂时不支持其他类型
                break;
        }
        if (needRefresh) {
            refreshUsers();
        }
    }
};

// 复制用户选择的公司和部门下拉框内容
function cloneUserSlt() {
    $('#dplCom options').clone().appendTo('#dg_sltComps');
    $('#dplDepts options').clone().appendTo('#dg_sltDepts');
}